package com.caiheng.api.rabbitmq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * rabbitmq发送消息工具类
 *
 * @author chenhf
 * @create 2017-10-26 上午11:10
 **/

@Component
public class RabbitMqSender implements RabbitTemplate.ConfirmCallback {
    /** logger */
    private static final Logger logger = LoggerFactory.getLogger(RabbitMqSender.class);

    //由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE，所以不能自动注入
    private RabbitTemplate rabbitTemplate;

    /**
     * 构造方法注入rabbitTemplate
     */
    @Autowired
    public RabbitMqSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        this.rabbitTemplate.setConfirmCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        logger.info("confirm: " + correlationData.getId());
        logger.info(" 回调id:" + correlationData);
        if (b) {
            logger.info("消息成功消费");
        } else {
            logger.info("消息消费失败:" + s);
        }
    }

    /**
     *  点对点 方式
     * 发送到 指定routekey的指定queue
     * @param routeKey
     * @param content
     */
    public void sendRabbitmqDirect(String routeKey,Object content) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        logger.info("send: " + correlationData.getId());
        this.rabbitTemplate.convertAndSend(RabbitMqEnum.Exchange.CONTRACT_DIRECT.getCode(), routeKey , content, correlationData);
    }

//    /**
//     *  Topic 消息订阅方式
//     * 所有发送到Topic Exchange的消息被转发到所有关心RouteKey中指定Topic的Queue上
//     * @param routeKey
//     * @param obj
//     */
//    public void sendRabbitmqTopic(String routeKey,Object obj) {
//        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
//        logger.info("send: " + correlationData.getId());
//        this.rabbitTemplate.convertAndSend(RabbitMqEnum.Exchange.CONTRACT_TOPIC.getCode(), routeKey , obj, correlationData);
//    }
}
